package com.oj.ojbackendjudgeservice.judge;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.oj.ojbackendcommon.common.ErrorCode;
import com.oj.ojbackendcommon.exception.BusinessException;
import com.oj.ojbackendjudgeservice.judge.codesandbox.CodeSandbox;
import com.oj.ojbackendjudgeservice.judge.codesandbox.CodeSandboxProxy;
import com.oj.ojbackendjudgeservice.judge.codesandbox.CodeSandboxFactory;
import com.oj.ojbackendjudgeservice.judge.strategy.JudgeContext;
import com.oj.ojbackendserviceclient.service.QuestionFeignClient;
import ojbackendmodel.model.codesandbox.ExecuteCodeRequest;
import ojbackendmodel.model.codesandbox.ExecuteCodeResponse;
import ojbackendmodel.model.codesandbox.JudgeInfo;
import ojbackendmodel.model.dto.question.JudgeCase;
import ojbackendmodel.model.entity.Question;
import ojbackendmodel.model.entity.QuestionSubmit;
import ojbackendmodel.model.enums.CodeSandboxStatusEnum;
import ojbackendmodel.model.enums.JudgeInfoMessageEnum;
import ojbackendmodel.model.enums.QuestionSubmitStatusEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService{

    @Resource
    private QuestionFeignClient questionFeignClient;

    @Value("${codesandbox.type:example}")
    private String type;

    @Resource
    private JudgeManager judgeManager;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        // 1.传入题目的提交 id ，获取到对应的题目，提交信息（包含代码、编程语言等）
        QuestionSubmit questionSubmit = questionFeignClient.getQuestionSubmitById(questionSubmitId);
        if (questionSubmit == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionFeignClient.getQuestionById(questionId);
        if (question == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目信息不存在");
        }

        // 2.如果题目提交状态不为等待中，就不用重复执行了
        if (!Objects.equals(questionSubmit.getStatus(), QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目正在判题中");
        }

        // 3.更改判题（题目提交）的状态为“判题中”，防止重复执行
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if (!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新错误");
        }

        // 4.调用沙箱，获取到执行结果 (代码执行模块)
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        String judgeCase = question.getJudgeCase();
        // todo 优化 json 转 list
        long l = System.currentTimeMillis();
        List<JudgeCase> judgeCaseList = JSON.parseArray(judgeCase, JudgeCase.class);
        // List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCase, JudgeCase.class);
        long l1 = System.currentTimeMillis();
        System.out.println("沙箱时间： " + (l1 - l));

        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());


        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);

        // 5.根据沙箱的执行结果，设置题目的判题状态和信息 (代码判断模块)
        /**
         * 判断逻辑：
         * 1.先判断沙箱执行的结果输出数量是否和预期输出数量相等
         * 2.依此判断每一项输出和预期输出是否相等
         * 3.判断题目的限制是否符合要求
         * 4.根据返回的 status,修改数据库中的 submitNum,acceptedNum
         * 5.可能还有其他的异常情况
         */
        System.out.println("输出结果：" + executeCodeResponse.getOutputList());
        System.out.println("输出状态：" + executeCodeResponse.getStatus());
        System.out.println("输出信息：" + executeCodeResponse.getMessage());
        JudgeInfo judgeInfo = executeCodeResponse.getJudgeInfo();
        List<String> outputList = executeCodeResponse.getOutputList();
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(judgeInfo);
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        JudgeInfo info = judgeManager.doJudge(judgeContext);
        System.out.println("输出info：" + info);
        // 6.修改数据库中的判题结果
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        if (!JudgeInfoMessageEnum.ACCEPTED.getValue().equals(info.getMessage())){
            questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.FAILED.getValue());
        }else {
            Integer acceptedNum = question.getAcceptedNum();
            Integer submitNum = question.getSubmitNum();
            //通过数+1
            acceptedNum=acceptedNum+1;
            question.setAcceptedNum(acceptedNum);
            //总数+1
            submitNum=submitNum+1;
            question.setSubmitNum(submitNum);
            questionFeignClient.updateQuestion(question);
            questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        }
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(info));
        update = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }
        QuestionSubmit questionSubmitResult = questionFeignClient.getQuestionSubmitById(questionId);
        return questionSubmitResult;

    }
}
